
import PySide6
from PySide6 import QtCore
from PySide6.QtWidgets import QGraphicsItem
from PySide6.QtCore import QRectF, QSize, QObject
from PySide6.QtGui import Qt, QPen, QPixmap
import my_graphics_scene

'''
关闭图形项，作为控制点。继承QObject主要是为使用信号和槽 
'''
class CloseCtrlItem(QGraphicsItem, QObject):

    closeSignal = QtCore.Signal(QGraphicsItem)   # 关闭。信号对象
    '''构造函数，radius为图形项的半径'''
    def __init__(self, radius, parent = None):
        QGraphicsItem.__init__(self, parent)
        QObject.__init__(self,None)
        self.__size = QSize(2 * radius, 2 * radius)  #图形项的大小
        self.__bgImage = QPixmap("./image/close.png")
        self.setFlag(QGraphicsItem.ItemIsFocusable)   # 让图形项可获取焦点
        
    ''' 重写 boundingRect 函数'''
    def boundingRect(self) -> PySide6.QtCore.QRectF:
        margin = 1   # 裕量，上下左右四个边界都留出一些裕量，方便绘制图形(特别是轮廓)
        return QRectF(0 - self.__size.width() / 2.0 - margin, 0 - self.__size.height() / 2.0 - margin, 
                      self.__size.width() + 2 * margin, self.__size.height() + 2 * margin)


    '''重写 paint 函数'''
    def paint(self, painter: PySide6.QtGui.QPainter, option: PySide6.QtWidgets.QStyleOptionGraphicsItem, widget) -> None:
        pen = QPen()
        pen.setWidth(1)
        pen.setColor(Qt.red)
        pen.setStyle(Qt.DashLine)  # 虚线
        painter.setPen(pen)
        # 绘制椭圆外形
        painter.drawEllipse(self.rect().x(), self.rect().y(), self.__size.width(), self.__size.height() )
        # 绘制背景图
        painter.drawPixmap(self.rect().x(), self.rect().y(), 
                           self.rect().width(), self.rect().height(), self.__bgImage)


    '''重写鼠标按下事件'''
    def mousePressEvent(self, event: PySide6.QtWidgets.QGraphicsSceneMouseEvent) -> None:
        if self.scene() != None and isinstance(self.scene(), my_graphics_scene.MyGraphicsScene) :
            self.closeSignal.connect(self.scene().removeItem)
         # 发送关闭信号
        if self.parentItem() != None :
            self.closeSignal.emit(self.parentItem()) 
        else :
            self.closeSignal.emit(self)
        # return QGraphicsItem.mousePressEvent(self, event)  # 对象已经要被删除了，没必要return了


    '''获取图形项矩形'''
    def rect(self) -> PySide6.QtCore.QRectF:
        return QRectF(0 - self.__size.width() / 2.0 , 0 - self.__size.height() / 2.0 , 
                      self.__size.width() , self.__size.height() )
